"""
自定义Redfish基础方法
"""
import requests
import json


class RequestBase:
    def __init__(self, host_ip, username, password):
        self.host = host_ip
        self.username = username
        self.password = password
        self.pre_url = "https://{}:443".format(self.host)
        self.se = requests.Session()
        self.headers = None

    def create_session(self):
        uri = "/redfish/v1/SessionService/Sessions"
        url = self.pre_url + uri
        headers = {"Content-Type": "application/json"}
        json = {"UserName": self.username, "Password": self.password}
        try:
            response = self.se.post(url=url, headers=headers, json=json, verify=False)
            if response.status_code != 201:
                print("Code status: {}".format(response.status_code))
                print(response.text)
                return response.status_code, response.json()
            self.headers = {'X-Auth-Token': response.headers['X-Auth-Token']}
            # print(f"\n======>>>>>>SessionID : {response.json()['Id']}")
            return response.status_code, response.json()['Id']

        except Exception as e:
            return None, f"ERROR INFO: {e}"

    def delete_session(self, session_id):
        uri = "/redfish/v1/SessionService/Sessions/{}".format(session_id)
        url = self.pre_url + uri
        try:
            response = self.se.delete(url=url, headers=self.headers, verify=False)
            return response.status_code, response.json()

        except Exception as e:
            return None, f"ERROR INFO: {e}"

    def get(self, url):
        turl = self.pre_url + url
        try:
            response = self.se.get(url=turl, headers=self.headers, verify=False)
            return response.status_code, response.json(), response.text

        except Exception as e:
            return None, f"ERROR INFO: {e}"

    def get_header(self, url):
        turl = self.pre_url + url
        try:
            response = self.se.get(url=turl, headers=self.headers, verify=False)
            return response.headers

        except Exception as e:
            return None, f"ERROR INFO: {e}"

    def get_header_detail(self, url):
        turl = self.pre_url + url
        try:
            response = self.se.get(url=turl, headers=self.headers, verify=False)
            return response.headers, response.status_code, response.json()

        except Exception as e:
            return None, f"ERROR INFO: {e}"

    def post(self, url, params: dict):
        turl = self.pre_url + url
        try:
            response = self.se.post(url=turl, json=params, headers=self.headers, verify=False)
            return response.status_code, response.json(), response.text

        except Exception as e:
            return None, f"ERROR INFO: {e}"

    def delete(self, url, dst_str):
        url = f"{self.pre_url}{url}/{dst_str}"
        try:
            response = self.se.delete(url=url, headers=self.headers, verify=False)
            return response.status_code, response.json(), response.text
        except Exception as e:
            return None, f"ERROR INFO: {e}"

    def patch(self, url, params: dict):
        turl = self.pre_url + url
        try:
            response = self.se.patch(url=turl, json=params, headers=self.headers, verify=False)
            return response.status_code, response.json(), response.text

        except Exception as e:
            return None, f"ERROR INFO: {e}"


class OpenUBMCRestful:
    def __init__(self, bmc_ip, username, password):
        self.bmc_ip = bmc_ip
        self.username = username
        self.password = password
        self.session = None
        self.session_id = None

    def login(self):
        """登录到 BMC，创建会话"""
        login_url = f"https://{self.bmc_ip}/UI/Rest/Login"
        payload = {
            "UserName": self.username,
            "Password": self.password,
            "Type": "Local",
            "Domain": "LocaliBMC"
        }
        headers = {
            "Content-Type": "application/json"
        }

        self.session = requests.Session()
        self.session.verify = False  # 忽略证书验证
        self.session.headers.update(headers)

        try:
            response = self.session.post(login_url, data=json.dumps(payload))
            if response.status_code == 200:

                self.session_id = response.json()['Session']['SessionID']
                self.session.headers['X-Csrf-Token'] = response.json()['XCSRFToken']
                return True
            else:
                self.session = None
                return False
        except Exception as e:
            self.session = None
            return False

    def logout(self):
        """清理会话"""
        if self.session:
            logout_url = f"https://{self.bmc_ip}/UI/Rest/Sessions/{self.session_id}"
            response = self.session.delete(logout_url)
            return response.status_code, response.json()

